package com.geeker.module.sys.dict.sevice;

import com.geeker.common.exception.BusinessException;
import com.geeker.module.common.util.DictUtils;
import com.geeker.module.sys.dict.domain.SysDictData;
import com.geeker.module.sys.dict.mapper.SysDictDataMapper;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SysDictDataService extends ServiceImpl<SysDictDataMapper, SysDictData> {

    public List<SysDictData> getByDictType(String dictType) {
        List<SysDictData> dictDatas = DictUtils.getDictCache(dictType);
        if (CollectionUtils.isNotEmpty(dictDatas)) {
            return dictDatas;
        }
        dictDatas = selectDictDataByType(dictType);
        if (CollectionUtils.isEmpty(dictDatas)) {
            return null;
        }
        DictUtils.setDictCache(dictType, dictDatas);
        return dictDatas;
    }

    public boolean add(SysDictData data) {
        boolean save = this.save(data);
        if (save) {
            List<SysDictData> dictDatas = selectDictDataByType(data.getDictType());
            DictUtils.setDictCache(data.getDictType(), dictDatas);
        }
        return save;
    }

    public boolean edit(SysDictData data) {
        boolean bool = this.updateById(data);
        if (bool) {
            List<SysDictData> dictDatas = selectDictDataByType(data.getDictType());
            DictUtils.setDictCache(data.getDictType(), dictDatas);
        }
        return bool;
    }

    public void delete(List<Long> dictCodes) {
        for (Long dictCode : dictCodes) {
            SysDictData data = getById(dictCode);
            if(data == null)
                throw new BusinessException("参数错误");
            this.removeById(dictCode);
            List<SysDictData> dictDatas = selectDictDataByType(data.getDictType());
            DictUtils.setDictCache(data.getDictType(), dictDatas);
        }
    }

    public List<SysDictData> selectDictDataByType(String dictType) {
        return this.list(QueryWrapper.create().eq(SysDictData::getDictType, dictType));
    }
}
